import React, { useState, useEffect } from 'react';
import { GetUrl } from './GetUrl';
import SidePanel from './SidePanel';
import { collectUrl } from '../service';
import { createRoot } from 'react-dom/client';
import { Button, notification, Spin, Alert, Typography } from 'antd';
import { ReadOutlined, SmileOutlined } from '@ant-design/icons';
import { KNOWLEDGE_LIB_ROUTER } from '../constants';

// Define the CollectionManager namespace and its types
export namespace CollectionManager {
    // Replace enum with string constants
    export const Action = {
        StartCollection: 'StartCollection',
        ShowSidePanel: 'ShowSidePanel',
        CloseSidePanel: 'CloseSidePanel'
    } as const;

    export type Message = {
        id: string
        action: string  // 只使用字符串类型
        data?: any
    }
}

/**
 * 收藏管理器 - 管理收藏流程和侧滑面板显示
 */
export namespace CollectionManager {
    export const id = 'COLLECTION_MANAGER'
    
    // 状态管理
    let sidePanelVisible = false;
    let currentInfoGuid = '';
    let currentUserGuid = 'f62e6504-0564-4958-a757-0d84e0ea2e79'; // 默认用户GUID，实际应该从存储中获取
    
    /**
     * 消费消息
     * @param message 
     * @returns 
     */
    export const consume = async (message: Message) => {
        console.log('CollectionManager.consume 被调用，消息详情:', message);
        console.log('消息ID:', message.id);
        console.log('消息动作:', message.action);
        console.log('是否匹配StartCollection:', message.action === "StartCollection");
        // 只使用字符串比较
        if (message.action === Action.StartCollection) {
            // 开始收藏流程
            console.log('Starting collection process...')
            return await handleStartCollection(message);
        }

        if (message.action === Action.ShowSidePanel) {
            // 显示侧滑面板
            console.log('Showing side panel...')
            return handleShowSidePanel(message);
        }

        if (message.action === Action.CloseSidePanel) {
            // 关闭侧滑面板
            console.log('Closing side panel...')
            return handleCloseSidePanel();
        }

        console.log('Unknown action:', message.action)
        return { message: 'Unknown action' };
    }

    // 通知相关常量
    const key = 'updatable';
    const { Title, Text } = Typography;
    
    /**
     * 处理开始收藏
     */
    const handleStartCollection = async (message: Message) => {
        console.log('handleStartCollection 被调用 - handleStartCollection called');
        try {
            // 显示收藏中通知
            console.log('显示收藏中通知 - Showing collecting notification');
            showCollectingNotification();
            
            // 获取用户信息
            console.log('获取用户信息 - Getting user info');
            const result = await chrome.storage.local.get('user');
            console.log('用户信息结果 - User info result:', result);
            const user = result.user;
            
            if (!user) {
                console.error('用户未登录 - User not logged in');
                showErrorNotification('User not logged in');
                return {
                    message: 'error',
                    error: 'User not logged in'
                };
            }
            
            // 更新当前用户GUID
            console.log('更新用户GUID - Updating user GUID:', user.userGuid);
            currentUserGuid = user.userGuid;
            
            // 获取页面内容
            console.log('获取页面内容 - Getting page content');
            const content = document.body?.innerText || '';
            const url = window.location?.href || 'https://example.com';
            const title = window.document?.title || 'No Title';
            console.log('页面信息 - Page info:', { url, title, contentLength: content.length });
            
            // 第一次尝试收藏（空内容）
            console.log('调用collectUrl API - Calling collectUrl API (first attempt)');
            let response;
            try {
                response = await collectUrl({
                    url,
                    title,
                    content: "", // 首次请求发送空字符串
                    userGuid: user.userGuid,
                    accessToken: user.accessToken,
                    num: 1
                });
                console.log('收藏响应结果 - Collection response (first attempt):', response);
            } catch (apiError) {
                console.error('收藏 API 调用失败 - Collection API call failed (first attempt):', apiError);
            }
            
            // 如果第一次失败，尝试发送完整内容
            if (!response || !response.isSuccess) {
                console.log('第一次收藏失败，尝试第二次 - First attempt failed, trying second attempt');
                try {
                    response = await collectUrl({
                        url,
                        title,
                        content, // 第二次请求发送实际内容
                        userGuid: user.userGuid,
                        accessToken: user.accessToken,
                        num: 2
                    });
                    console.log('收藏响应结果 - Collection response (second attempt):', response);
                } catch (apiError) {
                    console.error('收藏 API 调用失败 - Collection API call failed (second attempt):', apiError);
                }
            }

            if (response && response.isSuccess && response.data) {
                // 收藏成功，保存infoGuid并显示侧滑面板
                currentInfoGuid = response.data;
                showSuccessNotification();
                return showSidePanel();
            } else {
                const errorMsg = response?.message || 'Collection failed';
                showErrorNotification(errorMsg);
                throw new Error(errorMsg);
            }
        } catch (error) {
            console.error('Collection error:', error);
            showErrorNotification(error.message || 'Collection failed');
            return {
                message: 'error',
                error: error.message || 'Collection failed'
            };
        }
    }
    
    /**
     * 显示收藏中通知
     */
    const showCollectingNotification = () => {
        notification.success({
            key,
            message: 'InfoKeyMind',
            icon: <SmileOutlined style={{ color: '#108ee9' }} />,
            description: (
                <>
                    <Spin spinning={true} size="large">
                        <div>
                            <Title level={3} type="secondary" style={{ color: 'blue' }}>Saving in progress...</Title>
                        </div>
                    </Spin>
                </>
            ),
            duration: null,
            btn: (
                <Button
                    type="primary"
                    icon={<ReadOutlined />}
                    onClick={() => {
                        window.open(KNOWLEDGE_LIB_ROUTER)
                    }}
                >
                    Open the knowledge base
                </Button>
            ),
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    }
    
    /**
     * 显示收藏成功通知
     */
    const showSuccessNotification = () => {
        notification.success({
            key,
            message: 'InfoKeyMind',
            icon: <SmileOutlined style={{ color: '#108ee9' }} />,
            description: (
                <>
                    <div>
                        <Title level={3} type="secondary" style={{ color: 'green' }}>Saved to InfoKeyMind!!</Title>
                    </div>
                </>
            ),
            btn: (
                <Button
                    type="primary"
                    icon={<ReadOutlined />}
                    onClick={() => {
                        window.open(KNOWLEDGE_LIB_ROUTER)
                    }}
                >
                    Open the knowledge base
                </Button>
            ),
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    }
    
    /**
     * 显示错误通知
     */
    const showErrorNotification = (errorMessage: string) => {
        notification.error({
            key,
            message: 'InfoKeyMind',
            icon: <SmileOutlined style={{ color: '#ff4d4f' }} />,
            description: (
                <>
                    <div>
                        <Title level={3} type="danger" style={{ color: '#ff4d4f' }}>
                            Collection Failed!
                        </Title>
                        {errorMessage && (
                            <Text type="secondary" style={{ color: '#8c8c8c', fontSize: '14px' }}>
                                {errorMessage}
                            </Text>
                        )}
                    </div>
                </>
            ),
            btn: (
                <Button
                    type="primary"
                    danger
                    icon={<ReadOutlined />}
                    onClick={() => {
                        window.open(KNOWLEDGE_LIB_ROUTER)
                    }}
                >
                    Try Again
                </Button>
            ),
            onClick: () => {
                console.log('Error Notification Clicked!');
            },
        });
    }

    /**
     * 处理显示侧滑面板
     */
    const handleShowSidePanel = (message: Message) => {
        if (message.data?.infoGuid) {
            currentInfoGuid = message.data.infoGuid;
        }
        return showSidePanel();
    }

    /**
     * 显示侧滑面板
     */
    const showSidePanel = () => {
        console.log('showSidePanel called with infoGuid:', currentInfoGuid, 'userGuid:', currentUserGuid)
        sidePanelVisible = true;
        
        try {
            // 检查document和body是否可用
            console.log('Document ready state:', document.readyState);
            console.log('Body exists:', !!document.body);
            
            // 创建侧滑面板元素
            const existingPanel = document.getElementById('ai-side-panel');
            if (existingPanel) {
                console.log('Removing existing panel')
                existingPanel.remove();
            }

            // 创建一个简单的测试元素，验证DOM操作是否正常
            const testElement = document.createElement('div');
            testElement.id = 'test-element';
            testElement.textContent = 'Test Element';
            testElement.style.cssText = `
                position: fixed !important;
                top: 10px !important;
                right: 10px !important;
                padding: 10px !important;
                background: red !important;
                color: white !important;
                z-index: 2147483647 !important;
            `;
            console.log('Appending test element to body');
            document.body.appendChild(testElement);
            console.log('Test element appended successfully');

            const panelContainer = document.createElement('div');
            panelContainer.id = 'ai-side-panel';
            panelContainer.style.cssText = `
                position: fixed !important;
                top: 0 !important;
                right: 0 !important;
                width: 350px !important;
                height: 100vh !important;
                z-index: 2147483647 !important;
                pointer-events: auto !important;
                background: white !important;
                box-shadow: -2px 0 10px rgba(0, 0, 0, 0.2) !important;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
            `;
            
            // 添加一个简单的内容，不依赖React
            const simpleContent = document.createElement('div');
            simpleContent.style.cssText = `
                padding: 20px !important;
                color: black !important;
                font-size: 16px !important;
            `;
            simpleContent.innerHTML = `
                <h2 style="margin-bottom: 15px !important;">Collection Successful!</h2>
                <p>Your content has been saved successfully.</p>
                <p>Info GUID: ${currentInfoGuid}</p>
                <button id="close-panel-btn" style="
                    margin-top: 20px !important;
                    padding: 8px 16px !important;
                    background: #1677ff !important;
                    color: white !important;
                    border: none !important;
                    border-radius: 4px !important;
                    cursor: pointer !important;
                ">Close Panel</button>
            `;
            panelContainer.appendChild(simpleContent);
            
            console.log('Appending panel to body')
            document.body.appendChild(panelContainer);
            
            // 添加关闭按钮事件
            setTimeout(() => {
                const closeBtn = document.getElementById('close-panel-btn');
                if (closeBtn) {
                    closeBtn.addEventListener('click', () => {
                        console.log('Close button clicked');
                        handleCloseSidePanel();
                    });
                    console.log('Close button event listener added');
                } else {
                    console.error('Close button not found');
                }
            }, 100);

            // 尝试使用React渲染侧滑面板
            try {
                console.log('Creating React root and rendering SidePanel');
                const root = createRoot(panelContainer);
                root.render(
                    React.createElement(SidePanel, {
                        visible: true,
                        onClose: () => {
                            console.log('Side panel close requested');
                            handleCloseSidePanel();
                            root.unmount();
                        },
                        infoGuid: currentInfoGuid,
                        userGuid: currentUserGuid
                    })
                );
                console.log('Side panel rendered successfully with React');
            } catch (reactError) {
                console.error('React rendering failed:', reactError);
                // React渲染失败，但我们已经有了简单的HTML内容
                console.log('Falling back to simple HTML content');
            }
            
            return {
                message: 'Side panel shown',
                data: {
                    infoGuid: currentInfoGuid,
                    visible: true
                }
            };
        } catch (error) {
            console.error('Error showing side panel:', error);
            // 尝试使用alert显示错误
            try {
                alert('Failed to show side panel: ' + (error as Error).message);
            } catch (alertError) {
                console.error('Even alert failed:', alertError);
            }
            return {
                message: 'error',
                error: 'Failed to show side panel: ' + (error as Error).message
            };
        }
    }

    /**
     * 处理关闭侧滑面板
     */
    const handleCloseSidePanel = () => {
        sidePanelVisible = false;
        
        const panelElement = document.getElementById('ai-side-panel');
        if (panelElement) {
            panelElement.remove();
        }

        return {
            message: 'Side panel closed',
            data: {
                visible: false
            }
        };
    }

    /**
     * 获取当前状态
     */
    export const getState = () => ({
        sidePanelVisible,
        currentInfoGuid,
        currentUserGuid
    });

    /**
     * 创建开始收藏动作
     */
    export const createStartCollectionAction = () => {
        console.log('创建开始收藏消息 - Creating start collection message');
        return {
            id: id,
            action: 'StartCollection'
        };
    };

    /**
     * 创建显示侧滑面板动作
     */
    export const createShowSidePanelAction = (infoGuid?: string) => {
        console.log('创建显示侧滑面板消息 - Creating show side panel message');
        return {
            id: id,
            action: 'ShowSidePanel',
            data: infoGuid ? { infoGuid } : undefined
        };
    };

    /**
     * 创建关闭侧滑面板动作
     */
    export const createCloseSidePanelAction = () => {
        console.log('创建关闭侧滑面板消息 - Creating close side panel message');
        return {
            id: id,
            action: 'CloseSidePanel'
        };
    };
}

export default CollectionManager;
